# gpuWrapper.R
# Simple wrapper function for GPU and CPU functions, deploying them based on
# whatever node it's on. The GPU and CPU functions both need to take the
# same input signatures
#
# Author: Jack Chua
# 

# define our node map - this tells R which nodes are GPU-enabled and
# which ones aren't on our cluster
nodes <- c("jinx-login", "jinx1", "jinx2", "jinx3", "jinx4", "jinx5", "jinx6", "jinx7", "jinx8", "jinx9", "jinx10", "jinx11", "jinx12", "jinx13", "jinx14", "jinx15", "jinx16", "jinx17", "jinx18", "jinx19", "jinx20", "jinx21", "jinx22", "jinx23", "jinx24")
gpu <- c(0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
nodeMap <- data.frame(cbind(nodes, gpu))
                        
# simple wrapper for GPU and CPU functions, deploying them based on whatever
# node it's on. the GPU and CPU functions both need to take have
# the same input signatures

gpuFuncWrap <- function(data, gpuFunc, cpuFunc, nodeMap, ...) {
    #find out which node we're on
    nodeName <- system("hostname", intern=TRUE)
    
    if (nodeName %in% nodeMap$nodes) {
        #node is known
        #check if we should use the GPU version
        gpuEnabled <- nodeMap[nodeMap$nodes == nodeName,2]

        if (gpuEnabled == 1) {
            res <- gpuFunc(data, ...)
            return(res)
        }
        else {
            res <- cpuFunc(data, ...)
            return(res)
        }
    }
    else {
        #unknown node. assume we use CPU implementation
        res <- cpuFunc(data, ...)
        return(res)
    }
}
